<?php
class SeminarBatchType_Controller extends AdminController {

    public $DISPLAY_LOCALIZED_VALUE_LIST_UUID = 'admin/seminarBatchType/display/localizedValueList';

    public function __construct() {
        parent::__construct('seminarBatchType');
        $this->setDefaultListOrder('code');
    }

    function all() {
        $this->initPagination('batch_type');

        $this->viewData['seminarBatchTypeList'] = $this->dao->queryAll($this->orderLimitAndOffset(
                'SELECT pv.*, l10n.* ' .
                'FROM batch_type pv ' .
                'LEFT OUTER JOIN batch_type_l10n l10n ON pv.code = l10n.batch_type_code AND l10n.language_code = :language_code'),
                array('language_code' => $this->getLocalLanguageCode()));
        $this->renderSubview('admin/seminarBatchType/seminarBatchTypeList');
    }

    function display() {
        $code = $this->input->get('code');

        if (! valid::isCode($code)) {
            $this->redirectToList('error.invalidId');
        }

        $seminarBatchType = $this->dao->getLocalizedEntityByCode('batch_type', $code, $this->getLocalLanguageCode());
        if (! $seminarBatchType) {
            $this->redirectToList('error.recordNotFound');
        }
        $this->viewData['seminarBatchType'] = $seminarBatchType;

        $this->viewData['seminarBatchTypeL10nList'] = $this->dao->queryAll(sql::orderBy($this->DISPLAY_LOCALIZED_VALUE_LIST_UUID,
                'SELECT egl.*, l.name as language_name FROM batch_type_l10n egl ' .
                'LEFT OUTER JOIN language l ON l.code = egl.language_code ' .
                'WHERE egl.batch_type_code = :code', 'code'),
                array('code' => $code));

        $this->renderSubview('admin/seminarBatchType/seminarBatchTypeDisplay');
    }

    function edit() {
        // default values for a new record
        $seminarBatchType = array(
            'language_code' => $this->getLocalLanguageCode()
        );

        $this->loadFormData();

        $this->viewData['seminarBatchType'] = $seminarBatchType;
        $this->renderSubview('admin/seminarBatchType/seminarBatchTypeEdit');
    }

    protected function loadFormData() {
        $this->viewData['languageOptions'] = $this->dao->queryOptions(
                'SELECT l.code, l.name ' .
                'FROM language l ' .
                'ORDER BY l.name');
    }

    function save() {
        $formData = $this->postToDbValues();
        $code = $formData['code'];
        $this->viewData['seminarBatchType'] = $formData;

        // Basic validation
        $validator = new EntityValidator($formData, 'seminarBatchType', $this->msg);
        $validator->code('code');
        $validator->code('code_part');
        $validator->maxLength('code_part', 3);
        $validator->code('language_code');
        $validator->required('name');
        $validator->required('description');

        if ($this->msg->hasErrors()) {
            $this->loadFormData();
            $this->publishErrors('admin/seminarBatchType/seminarBatchTypeEdit');
            return;
        }
        
        // Database validation
        $existingEntity = $this->dao->getLocalizedEntityByCode('batch_type', $code, $this->getLocalLanguageCode());
        if (! sql::isPersistent($formData)) {
        	// Unique name
        	if ($existingEntity) {
        		$this->msg->error('batchType.error-alreadyExists-code', $code);
        	}
        	$count = $this->dao->queryCount(
        			'SELECT count(*) FROM batch_type_l10n egl ' .
        			'WHERE batch_type_code = :code ' .
        			'AND language_code = :language_code',
        			array('code' => $code, 'language_code' => $formData['language_code']));
        	if ($count > 0) {
        		$this->msg->error('seminarBatchType.error-alreadyExists-name', $formData['name']);
        	}
        }
        else {
        	if (! $existingEntity) {
        		$this->msg->error('error.recordNotFound');
        	}
        }
        if ($this->msg->hasErrors()) {
        	$this->loadFormData();
        	$this->publishErrors('admin/seminarBatchType/seminarBatchTypeEdit');
        	return;
        }
        
        // Insert or update
        $entity = new BatchTypeEntity($formData);
        if ($entity->isPersistent()) {
        	$this->dao->updateEntity($entity);
        	$this->msg->info('seminarBatchType.editSuccess', $existingEntity['name']);
        }
        else {
        	$this->dao->insertEntity($entity);
        
        	// Insert localized values
        	$l10nEntity = new BatchTypeL10nEntity($formData);
        	$this->dao->insertEntity($l10nEntity);
        	$this->msg->info('seminarBatchType.createSuccess', $l10nEntity->get('name'));
        }
        
        $this->ajaxSuccessOrRedirect('/admin/seminarBatchType/all', $formData);
    }

    function delete() {
        $code = $this->input->get('code');

        if (! valid::isCode($code)) {
            $this->redirectToList('error.invalidId');
        }

        // Basic validation
        $seminarBatchType = $this->dao->getLocalizedEntityByCode('batch_type', $code, $this->getLocalLanguageCode());
        if (! $seminarBatchType) {
            $this->redirectToList('error.recordNotFound');
        }

        // Delete the record, localization values are deleted by cascading.
        $this->dao->deleteByCode('batch_type', $code);

        $this->msg->info('seminarBatchType.deleteSuccess', $seminarBatchType['name']);
        $this->redirectToList();
    }

    function editLocalizedValues() {
        $code = $this->input->get('batch_type_code');
        $languageCode = $this->input->get('language_code');

        if (! valid::isCode($code)) {
            $this->redirectToList('error.invalidId');
        }

        $seminarBatchType = $this->dao->getLocalizedEntityByCode('batch_type', $code, $this->getLocalLanguageCode());
        if (! $seminarBatchType) {
            $this->redirectToList('error.recordNotFound');
        }
        $this->viewData['seminarBatchType'] = $seminarBatchType;

        if (valid::isCode($languageCode)) {
            $seminarBatchTypeL10n = $this->dao->getUnique('batch_type_l10n',
                    array(
                        'batch_type_code' => $code,
                        'language_code' => $languageCode
                    ));
            if (! $seminarBatchTypeL10n) {
                $this->redirectToList('error.recordNotFound');
            }
        }
        else {
            // Default values
            $seminarBatchTypeL10n = array('batch_type_code' => $code);
        }
        $this->viewData['seminarBatchTypeL10n'] = $seminarBatchTypeL10n;

        $this->localizedValuesData($code, $languageCode);
        $this->renderMySubview('seminarBatchTypeL10nEdit');
    }

    function localizedValuesData($seminarBatchTypeCode, $languageCode) {
        $params = array('code' => $seminarBatchTypeCode);
        $query = 'SELECT l.code, l.name ' .
                    'FROM language l ' .
                    'WHERE l.code NOT IN (SELECT egl.language_code FROM batch_type_l10n egl WHERE egl.batch_type_code = :code) ';
        if ($languageCode) {
            $query .= 'OR l.code = :language_code ';
            $params['language_code'] = $languageCode;
        }
        $query .= 'ORDER BY l.name';
        $this->viewData['languageOptions'] = $this->dao->queryOptions($query, $params);
    }

    function saveLocalizedValues() {
        $seminarBatchTypeL10n = $this->postToDbValues();
        $code = $seminarBatchTypeL10n['batch_type_code'];
        $this->viewData['seminarBatchTypeL10n'] = $seminarBatchTypeL10n;
        $languageCode = $seminarBatchTypeL10n['language_code'];
        if (! valid::isCode($code)) {
            $this->redirectToList('error.invalidId');
        }

        $seminarBatchType = $this->dao->getLocalizedEntityByCode('batch_type', $code, $this->getLocalLanguageCode());
        if (! $seminarBatchType) {
            $this->redirectToList('error.recordNotFound');
        }
        $this->viewData['seminarBatchType'] = $seminarBatchType;

        // Basic validation
        $validator = new EntityValidator($seminarBatchTypeL10n, 'seminarBatchType', $this->msg);
        $validator->code('language_code');
        $validator->required('name');
        $validator->required('description');
        if ($this->msg->hasErrors()) {
            $this->localizedValuesData($code, $languageCode);
            $this->publishErrors('admin/seminarBatchType/seminarBatchTypeL10nEdit');
            return;
        }

        $language = $this->dao->getByCode('language', $languageCode);
        if (! $language) {
            $this->redirectToList('error.recordNotFound');
        }

        if (! sql::isPersistent($seminarBatchTypeL10n)) {
            // Check if we don't already have this language
            $existingL10n = $this->dao->getUnique('batch_type_l10n', array(
                'batch_type_code' => $code,
                'language_code' => $languageCode
            ));
            if ($existingL10n) {
                $this->msg->error('errors.translationAlreadyExists', $language['name']);
                $this->localizedValuesData($code, $languageCode);
                $this->publishErrors('admin/seminarBatchType/seminarBatchTypeL10nEdit');
            }

            $this->dao->insert('batch_type_l10n', $seminarBatchTypeL10n);
            $this->msg->info('seminarBatchType.createL10nSuccess', $seminarBatchType['name'], $language['name']);
        }
        else {
            $this->dao->update('batch_type_l10n', $seminarBatchTypeL10n, array('batch_type_code', 'language_code'));
            $this->msg->info('seminarBatchType.editL10nSuccess', $seminarBatchType['name'], $language['name']);
        }

        $this->redirect('/admin/seminarBatchType/display?code=' . $code);
    }

    function deleteLocalizedValues() {
        $code = $this->input->get('batch_type_code');
        $languageCode = $this->input->get('language_code');

        if (! valid::isCode($code) || ! valid::isCode($languageCode)) {
            $this->redirectToList('error.invalidId');
        }

        $seminarBatchType = $this->dao->getLocalizedEntityByCode('batch_type', $code, $this->getLocalLanguageCode());
        if (! $seminarBatchType) {
            $this->redirectToList('error.recordNotFound');
        }

        $language = $this->dao->getByCode('language', $languageCode);
        if (! $language) {
            $this->redirectToList('error.recordNotFound');
        }

        $pk = array(
            'batch_type_code' => $code,
            'language_code' => $languageCode
        );

        $seminarBatchTypeL10n = $this->dao->getUnique('batch_type_l10n', $pk);
        if (! $seminarBatchTypeL10n) {
            $this->redirectToList('error.recordNotFound');
        }

        $this->dao->delete('batch_type_l10n', $pk);

        $this->msg->info('seminarBatchType.deleteL10nSuccess', $seminarBatchType['name'], $language['name']);
        $this->redirect('/admin/seminarBatchType/display?code=' . $code);
    }
}
